package com.onetime.mall.trading.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.onetime.mall.trading.constants.ErrorMsg;
import com.onetime.mall.trading.entity.IdleItemEntity;
import com.onetime.mall.trading.entity.OrderEntity;
import com.onetime.mall.trading.service.IdleItemService;
import com.onetime.mall.trading.service.OrderService;
import com.onetime.mall.trading.utils.OrderTaskHandler;
import com.onetime.mall.trading.utils.PageUtils;
import com.onetime.mall.trading.utils.R;
import com.onetime.mall.trading.utils.SnowFlake;
import com.onetime.mall.trading.vo.ItemUserVo;
import com.onetime.mall.trading.vo.OrdersAndProductsVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 订单表
 *
 * @author liyixuan
 * @email liyixuan106@163.com
 * @date 2022-03-26 19:38:29
 */
@RestController
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private IdleItemService idleItemServicel;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        System.out.println("新的订单管理：" + params);
        PageUtils page = orderService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        OrderEntity order = orderService.getById(id);

        return R.ok().put("order", order);
    }

    @RequestMapping("/get")
    public R getOrderInfo(@RequestParam("id") Long id) {
        OrderEntity order = orderService.getById(id);

        return R.ok().put("order", order);
    }

    @GetMapping("/info")
    public R getOrderInfo(@RequestParam("userId")
                          @NotNull(message = "登录异常 请重新登录")
                          @NotEmpty(message = "登录异常 请重新登录") String shUserId,
                          @RequestParam Long id) {
        /*查到订单信息*/
        OrderEntity orderEntity = orderService.getById(id);
        /*获得订单的商品id*/
        Long idleId = orderEntity.getIdleId();
        /*查到商品及发布者的信息*/
        ItemUserVo idleItem = idleItemServicel.getIdleItem(idleId);

        IdleItemEntity product = idleItemServicel.GetProductInformation(idleId);

        OrdersAndProductsVo ordersAndProductsVo = new OrdersAndProductsVo();
        BeanUtils.copyProperties(orderEntity, ordersAndProductsVo);
        ordersAndProductsVo.setIdleItem(product);
        /*获得商品的所有者id*/
        Long userId = idleItem.getUserId();

        return R.ok().put("data", ordersAndProductsVo);
        /*return R.error(ErrorMsg.SYSTEM_ERROR.getCode(), ErrorMsg.SYSTEM_ERROR.getMsg());*/
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    public R save(@RequestBody OrderEntity order) {
        orderService.save(order);

        return R.ok();
    }

    @PostMapping("/add")
    public R addOrder(@RequestParam("userId")
                      @NotNull(message = "登录异常 请重新登录")
                      @NotEmpty(message = "登录异常 请重新登录") String shUserId,
                      @RequestBody OrderEntity order) {

        if (OrderTaskHandler.orderService == null) {
            /*为订单事务处理初始化订单服务*/
            OrderTaskHandler.orderService = orderService;
        }
        /*初始化订单基本信息*/
        order.setOrderNumber(SnowFlake.getID().toString());
        order.setCreateTime(new Date());
        order.setUserId(Long.valueOf(shUserId));
        order.setOrderStatus(0);
        order.setPaymentStatus(0);
        System.out.println("//////////////////////");
        System.out.println(order);
        OrderEntity one = orderService.getOne(new QueryWrapper<OrderEntity>().eq("idle_id", order.getIdleId()).eq("user_id",order.getUserId()));
        if (one != null){
            return R.ok().put("data", one);
        }
        if (orderService.addOrder(order)) {
            return R.ok().put("data", order);
        }
        return R.error(ErrorMsg.SYSTEM_ERROR.getCode(), ErrorMsg.SYSTEM_ERROR.getMsg());
    }

    /**
     * 修改
     */
    @RequestMapping("/update1")
    public R update(@RequestBody OrderEntity order) {
        orderService.updateById(order);

        return R.ok();
    }

    @PostMapping("/update")
    public R updateOrder(@RequestParam("userId")
                         @NotNull(message = "登录异常 请重新登录")
                         @NotEmpty(message = "登录异常 请重新登录") String shUserId,
                         @RequestBody OrderEntity orderEntity) {
        /*if (orderEntity.getOrderStatus()==4){
            orderService.deleteOrder(orderEntity.getId());
            return R.ok();
        }*/
        if (orderEntity.getPaymentStatus() != null && orderEntity.getPaymentStatus().equals(1)) {
            orderEntity.setPaymentTime(new Date());
        }

        if (orderService.updateOrder(orderEntity)) {
            OrderEntity order = orderService.getById(orderEntity.getId());
            /*支付成功，设置支付时间*/
            IdleItemEntity item = idleItemServicel.getById(order.getIdleId());
            /*更改原来商品所属*/
            /*item.setUserId(order.getUserId());*/
            /*更改原来商品销售状态*/
            item.setIdleStatus(2);
            idleItemServicel.updateIdleItem(item);
            return R.ok().put("data", orderEntity);
        }
        return R.error(ErrorMsg.SYSTEM_ERROR.getCode(), ErrorMsg.SYSTEM_ERROR.getMsg());
    }

    @GetMapping("/my")
    public R getMyOrder(@RequestParam("userId")
                        @NotNull(message = "登录异常 请重新登录")
                        @NotEmpty(message = "登录异常 请重新登录") String shUserId) {
        List<OrdersAndProductsVo> list = orderService.getMyOrder(Long.valueOf(shUserId));
        return R.ok().put("data", list);
    }

    @GetMapping("/my-sold")
    public R getMySoldIdle(@RequestParam("userId")
                           @NotNull(message = "登录异常 请重新登录")
                           @NotEmpty(message = "登录异常 请重新登录") String shUserId) {
        Long userId = Long.valueOf(shUserId);
        List<OrdersAndProductsVo> list = orderService.getMySoldIdle(userId);
//        System.out.println("我卖出的订单：");
//        System.out.println(list);
        return R.ok().put("data", list);
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestParam("data") String ids) {
        String[] split = ids.split(",");
        List<Long> collect = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList());
        orderService.removeByIds(collect);

        return R.ok();
    }

}
